/*
* @Date: 2020/6/11
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import $ from 'jquery';
import React from 'react';
import componentsMap from './componentsMap';
export function parsePage(doc, page, index = 0) {
  const doms = doc.childNodes;
  if (doms.length === 0) {
    return;
  }
  const virtuals = [];
  for (let i = 0; i < doms.length; i++) {
    let virtualDom = null;
    if ($(doms[i]).hasClass('view-item-box')) {
      const id = $(doms[i]).attr('id');
      if (id) {
        virtualDom = page[id];
      } else {
        const componentName = $(doms[i]).attr('data-component');
        virtualDom = React.createElement(componentsMap[componentName], {});
      }
      let childrens = parsePage(doms[i], page, index + 1);
      const { props } = virtualDom;
      const targetProps = {
        ...props,
        children: childrens
      }
      const type = virtualDom.type;
      let domFlag = '';
      if (typeof type === 'function') {
        let funcName = /^function\s+([a-zA-Z]+[a-zA-Z0-9_]*)\s*\(/.exec(type.toString());
        domFlag = funcName[1].trim();
      }
      virtualDom = React.createElement(componentsMap[domFlag], targetProps);
    } else {
      virtualDom = parsePage(doms[i], page, index + 1);
    }
    if (!!virtualDom) {
      virtuals.push(virtualDom);
    }
  }
  return virtuals.length > 0 ? <React.Fragment>{virtuals}</React.Fragment> : null;
}
